#!/bin/bash
exec 2>/dev/null
LCM_COLOR_SCRIPT="/home/root/jabil/colorbarEx"
CAT_DELAY="0.1"

print_usage()
{
        echo "$0 <value>"
        echo "where <value> : 1 or Start, to start the test"
        echo "              : 0 or Stop, to stop the test"
}

if [ $# -ne 1 ];
then
        print_usage
        exit -1;
fi

case $1 in
        0|stop)
                kill -2 $(pidof colorbarEx)
                script_pid=$(ps| grep "[t]ouch_test.sh start" | awk '{print $1}')
                #echo $script_pid
                command_pid=$(ps| grep "[c]at /proc/kmsg" | awk '{print $1}')
                #echo $command_pid
                kill -9 $script_pid $command_pid
                modprobe -r evbug
                ;;
        1|start)
                modprobe evbug
                $LCM_COLOR_SCRIPT 1 &
                (
                        COORDINATE_FILE="/home/root/jabil/coordinates.txt"
                        EVENT_FILE="/tmp/event.txt"
                        count=0;
                        if [ -e $EVENT_FILE ]; then
                                rm $EVENT_FILE;
                        fi

                        if [ -e $COORDINATE_FILE ]; then
                                rm $COORDINATE_FILE
                        fi

                        touch $EVENT_FILE
                        touch $COORDINATE_FILE

                        echo "Touch anywhere on the screen"
                        while true;
                        do
                        cat /proc/kmsg > $EVENT_FILE &
                        sleep $CAT_DELAY
                        kill -9 $(ps| grep "[c]at /proc/kmsg" | awk '{print $1}')
                        
                        if [ -s $EVENT_FILE ]; then                                                       
                                x_value=$(grep 'Code: 53, Value:' $EVENT_FILE | head -n 1 | awk '{print $10}')
                                y_value=$(grep 'Code: 54, Value:' $EVENT_FILE | head -n 1 | awk '{print $10}')
                                rm $EVENT_FILE

                                if [ ! -z $x_value ]; then
                                echo "$count:x:$x_value,y:$y_value" | tee -a $COORDINATE_FILE
                                count=$((count+1))
                                fi
                        fi
                        done
                ) &
                exit 0;
                ;;
        *)
                echo "Invalid Argument"
                print_usage
                ;;
esac
